package com.jrx.anytxn.param.job.paph.step;

import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.RepayResult;
import com.jrx.anytxn.param.entity.TlFilePaymentLog;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class RepayResultProcessor implements ItemProcessor<RepayResult, TlFilePaymentLog> {
    @Autowired
    private ISegmentService segmentService;

    @Autowired
    private IOrganizationTableService organizationTableService;
    private static final Logger logger = LoggerFactory.getLogger(RepayResultProcessor.class);


    @Override
    public TlFilePaymentLog process(RepayResult repayResult) throws Exception {

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
        String tenantId = org.getTenantId();
        String loanId = repayResult.getLoanNo();
        String tradeDate = repayResult.getTradeDate();
        String tradeAmt = repayResult.getTradeAmt().toString();
        String tradeSeqNo = repayResult.getTradeSeqNo();
        String tradeFlag = repayResult.getTradeFlag();
        //转换日期
        Date date = DateUtils.parseDate(tradeDate, "yyyyMMdd");
        if (StringUtils.isBlank(loanId) || StringUtils.isBlank(tradeDate) ||
                StringUtils.isBlank(tradeAmt) || StringUtils.isBlank(tradeSeqNo) || StringUtils.isBlank(tradeFlag)) {
            Map<String, Object> map = BeanUtils.toMap(repayResult);
            logger.error("必输字段为空", map);
            throw new TxnException("必输字段为空");
        }

        TlFilePaymentLog tlFilePaymentLog = new TlFilePaymentLog();
        tlFilePaymentLog = BeanMapping.copy(repayResult, TlFilePaymentLog.class);
        tlFilePaymentLog.setLoanId(loanId);
        tlFilePaymentLog.setTenantId(tenantId);
        tlFilePaymentLog.setCreateTime(new Date());
        tlFilePaymentLog.setTradeDate(date);
        tlFilePaymentLog.setId(segmentService.getId(Constant.TL_FILE_PAYMENT_LOG));
        return tlFilePaymentLog;
    }
}
